#include <iostream>
//#include "myfileinfo.h"
#include "WebAndFileinfo.h"
#include "virus.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <tinyxml2.h>
#include <uuid/uuid.h>
#include <unistd.h>
#include <pwd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include "cJSON.h"
#include <dirent.h>
#include <sys/stat.h>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <fcntl.h>
#include <errno.h>
#include "process.h"  // 进程信息，包括入库
//#include "struct.h"
#include "publicFunc.h"
#include "baseInfo.h"	// 基础信息
#include "syslog.h"
#include <stdio.h>
#include <string.h>
#include "rockey.h"
#include <time.h>
#include "otp_interface.h"
#include "Base64.h"
using namespace tinyxml2;
using namespace std;

#define BUFFERSIZE 10240
typedef unsigned short WORD;
typedef unsigned int DWORD;
typedef unsigned char BYTE;

#define BUF_SIZE 2048
//#define _DEBUG_

static const int scnRow = 1000;

static map<string, int> mapMonth;
static vector<pair<string, string> > vFileAttackType;
static vector<pair<string, string> > vAttackToolType;


// 中间件日志解析规则
typedef struct WebRuler_
{
	char regex[64];         // 日志名正则
	char timeFmt[64];       // 时间格式
	char split[8];          // 分隔符
	char timeLocale[8];     // 时间字段中是否包含中文 英文:us 中文:cn 
	int timePosBeg;         // 时间所在列号-起始列号
	int timePsoEnd;         // 时间所在列号-结束列号-当只有一列时，结束列号为0
	int ipPst;              // ip所在列号
	int codePst;            // 相应码所在列号
	int bytePst;            // 相应字节数所在列号
}WebRuler, *pWebRuler;
/*
bool check()
{
	bool RES = false;

	unsigned int dwLP1 = 0;
	unsigned int dwLP2 = 0;
	

	//红探4号认证密码： 2016.1.26 YZM P1:44F6 P2:74E0 P3:E489 P4:EF88
	/////////////////////////////////////////////////////////////////////	
	unsigned short  wP1   = 0x44F6;
	unsigned short  wP2   = 0x74E0;
	unsigned short  wP3   = 0xE489;
	unsigned short  wP4   = 0xEF88;
	

	BYTE bBuffer[1024] ={"0"};
	int i = 0;
	int j = 0;
	int k = 0;

	unsigned short dwRet = 0;

	unsigned int  dwHandel[16];
	//Find Rockey4Smart
	dwRet = Rockey(RY_FIND,&dwHandel[0],&dwLP1,&dwLP2,&wP1,&wP2,&wP3,&wP4,bBuffer);
	if (dwRet != ERR_SUCCESS)
	{

		Rockey(RY_CLOSE,&dwHandel[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;

	}
	//Open Rockey4Smart
	dwRet = Rockey(RY_OPEN,&dwHandel[0],&dwLP1,&dwLP2,&wP1,&wP2,&wP3,&wP4,bBuffer);
	if (dwRet != ERR_SUCCESS)
	{

		Rockey(RY_CLOSE,&dwHandel[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	dwRet = Rockey(RY_VERSION,&dwHandel[0],&dwLP1,&dwLP2,&wP1,&wP2,&wP3,&wP4,bBuffer);
	if (dwRet)
	{

		Rockey(RY_CLOSE,&dwHandel[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	if (dwLP2 < 259)
	{
		Rockey(RY_CLOSE,&dwHandel[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	return true;
}*/
void GetMacAddr(char *cMac)
{
	int fd;
	int interfaceNum = 0;
	struct ifreq buf[16];
	struct ifconf ifc;
	struct ifreq ifrcopy;
	char mac[18] = {0};
	//char ip[32] = {0};
	//char broadAddr[32] = {0};
	//char subnetMask[32] = {0};


	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket");
		close(fd);
		return ;
	}

	ifc.ifc_len = sizeof(buf);
	ifc.ifc_buf = (caddr_t)buf;
	if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))
	{
		interfaceNum = ifc.ifc_len / sizeof(struct ifreq);
		//printf("interface num = %d\n", interfaceNum);
		while (interfaceNum-- > 0)
		{
			//printf("ndevice name: %s\n", buf[interfaceNum].ifr_name);
			ifrcopy = buf[interfaceNum];
			if (ioctl(fd, SIOCGIFFLAGS, &ifrcopy))
			{
				//printf("ioctl: %s [%s:%d]n", strerror(errno), __FILE__, __LINE__);
				close(fd);
				return ;
			}
			//get the mac of this interface  
			if (!ioctl(fd, SIOCGIFHWADDR, (char *)(&buf[interfaceNum])))
			{
				memset(mac, 0, sizeof(mac));
				snprintf(mac, sizeof(mac), "%02x-%02x-%02x-%02x-%02x-%02x",
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[0],
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[1],
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[2],
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[3],
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[4],
					(unsigned char)buf[interfaceNum].ifr_hwaddr.sa_data[5]
				);
				char * failMac = "00-00-00-00-00-00";
				//cout << "mac =" << mac << endl;
				if(strcmp(mac, failMac) != 0)
				{
					//printf("device mac: %s\n", mac);
					memcpy(cMac, mac, strlen(mac));
					break;
				}
			}
			else
			{
				//printf("ioctl: %s [%s:%d]n", strerror(errno), __FILE__, __LINE__);
				close(fd);
				return ;
			}

		}
	}

	close(fd);
}

bool HistoryResultToDb(sqlite3 *db, char *eventId) 
{
	FILE *fd;
	fd = fopen("./history", "rw");
	if(fd == NULL)
	{
		perror("open file failed3");
		return false;
	}

	//char *dbName = "./hongtan004_linux.db";
	//sqlite3 *db = NULL;
	char *err_msg;
	int rc;
	//rc = sqlite3_open(dbName, &db);
	//if(rc)
	//{
	//    perror("打开数据库失败！");
	//    return false;
	//}

	// 用户名
	char UserName[32] = {0};
	memset(UserName, 0, sizeof(char)*32);
	FILE *fp = NULL;
	fp = popen("pwd", "r");
	if(fp == NULL)
	{
		perror("err-history");
	}
	else
	{
		char userbuf[256];
		memset(userbuf, 0, sizeof(char)*256);
		if(fgets(userbuf, 255, fp) != NULL)
		{
			string str1 = strMid(userbuf, strFind(userbuf, "/home")+strlen("/home"));
			string str2 = StrLeft(str1, strFind(str1.c_str(), "/"));
			//cout << "用户名=" << str2<< endl;
			strncpy(UserName, str2.c_str(), 31);
		}
	}

	if(strlen(UserName) == 0)
	{
		struct passwd *pwd;
		pwd = getpwuid(getuid());
	
		strcpy(UserName, pwd->pw_name);
	}
	// 避免sql语句出错， 将字符串中的‘替换为’‘
	StrReplace(UserName, "'", "''");
	//cout << pwd->pw_name << endl;

	// Mac
	
	char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	char sql[1024] = {0};
	char buf[512] = {0};
	while(!feof(fd))
	{
		memset(buf, 0, sizeof(char)*512);
		if(fgets(buf, 511, fd) != NULL)
		{
			// UUID
			char str[36];
			memset(str, 0, sizeof(char)*36);
			//uuid_t uuid;
			//uuid_generate(uuid);
			//uuid_unparse(uuid, str);
			GetUUID(str, 36);

			StrReplace(buf, "'", "''");

			memset(sql, 0, sizeof(char)*1024);
			snprintf(sql, 1023, "insert into linux_history_file (id, user_name, history, mac_address, is_get_out, event_task_id) values('%s', '%s', '%s', '%s', '', '%s')", 
				str, UserName, buf, Mac, eventId);
			int ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
			if(ret != 0)
			{
				perror(err_msg);
				sqlite3_free(err_msg);
				//sqlite3_close(db);
				return false;
			}
			//printf("%s", buf);
		}
	}
	//sqlite3_close(db);

	return true;
}

// 通过日志结果中的josn文件， 获取中间件类型
// 1-apache, 2-tomcat, 3-nginx,
int GetWebType(char *JsonFile)
{
	int type = 0;
	FILE *fp;
	fp=fopen(JsonFile,"rb");
	if(fp == NULL)
	{
		perror("open file failed4");
		return -1;
	}

	string WebType;

	long len;
	char *data;
	fseek(fp,0,SEEK_END);
	len = ftell(fp);
	fseek(fp,0,SEEK_SET);
	data = new char [len+1];
	fread(data,1,len,fp);
	fclose(fp);

	cJSON *json;
	cJSON *Type;
	json = cJSON_Parse(data);
	if(!json)
	{
		perror("json is null 2");
		goto End;
	}

	Type = cJSON_GetObjectItem(json, "logType");
	//cout << Type->valuestring << endl;
	WebType = Type->valuestring;

	if(WebType.find("apache") != -1)
		type = 1;
	else if(WebType.find("tomcat") != -1)
		type = 2;
	else if(WebType.find("nginx") != -1)
		type = 3;
	else if(WebType.find("jboss") != -1)
		type = 4;
	else if(WebType.find("weblogic") != -1)
		type = 5;
	else
		type = 0;
  
End:
	cJSON_Delete(json);
	if(!data)
	{
		delete []data;
		data = NULL;
	}

	return type;
}

// Web文件结果入库
bool WebFileResultToDb(sqlite3 *db, const char *RstFile, char *EventId)
{
	tinyxml2::XMLDocument xmlDoc;
	XMLError eResult = xmlDoc.LoadFile(RstFile);
	XMLNode * pRoot = xmlDoc.RootElement();
	if(pRoot == NULL)
	{
		perror("xml file is null 1");
		return false;
	}

	char cTime[32] = {0};
	struct timeval tv;
	struct tm      stm;
	gettimeofday(&tv, NULL);
	localtime_r(&tv.tv_sec, &stm);
	strftime(cTime, 31, "%Y-%m-%d %H:%M:%S", &stm);
	//cout << "时间：" << cTime << endl;

	char *err_msg;

	// 操作系统
	const char * OsName = pRoot->FirstChildElement("os_version")->GetText();
	//cout << strlen(OsName) << endl;
	char cOsName[256] = {0};
	memset(cOsName, 0, sizeof(char)*256);
	strcpy(cOsName, OsName);
	//cout << cOsName << endl;
	StrReplace(cOsName, "'", "''");
	//cout << OsName << endl;

	// Mac
	//char mac[32] = {0};
	//GetMacAddr(mac);
char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	XMLElement *pElement = pRoot->FirstChildElement("match");
	if(pElement == NULL)
		return false;
	
	char sql[1024] = {0};

	pElement = pElement->FirstChildElement("base_match");
	while(pElement != NULL)
	{
		//printf("%s\n", pElement->Name());
		memset(sql, 0, sizeof(char)*1024);

		// UUID
		char str[36];
		memset(str, 0, sizeof(char)*36);
		//uuid_t uuid;
		//uuid_generate(uuid);
		//uuid_unparse(uuid, str);
		GetUUID(str, 36);
	
		const char * time = pElement->FirstChildElement("motime")->GetText();
		//printf("%s\n", time);
		const char * rule = pElement->FirstChildElement("rule_match")->GetText();
		//printf("%s\n", rule);
		const char * type = pElement->FirstChildElement("type")->GetText(); // ADWare.Badspeech APT.Malware APT.RAT Backdoor.Webshell
		int nType = 0;
		if(strstr(rule, "Badspeech") != NULL)
			nType = 3;
		else if(strstr(rule, "Apt") != NULL)
			nType = 2;
		else if(strstr(rule, "Webshell") != NULL)
			nType = 1;
		else
			nType = 0;
		
		//printf("%s\n", type);
		const char * desc = pElement->FirstChildElement("desc")->GetText();
		char cDesc[64] = {0};
		memset(cDesc, 0, sizeof(char)*64);
		strcpy(cDesc, desc);
		StrReplace(cDesc, "'", "''");
		//printf("%s\n", desc);
		const char * file = pElement->FirstChildElement("file")->GetText();
		char cFile[1024] = {0};
		memset(cFile, 0, sizeof(char)*1024);
		strcpy(cFile, file);
		StrReplace(cFile, "'", "''");
		//printf("%s\n", file);
		/*const char * stroffset = pElement->FirstChildElement("offset")->GetText();
		char cOffset[20];
		memset(cOffset,0,sizeof(char)*20);
		strcpy(cOffset,stroffset);
		StrReplace(cOffset, "'", "''");
		const char * strstring = pElement->FirstChildElement("string")->GetText();
		char cstring[1024];
		memset(cstring,0,sizeof(char)*1024);
		strcpy(cstring,strstring);
		StrReplace(cstring, "'", "''");*/
		XMLElement* pHashElement = pElement->FirstChildElement("hash");
		const char * md5 = pHashElement->FirstChildElement("md5")->GetText();
		//printf("%s\n", md5);
		const char * sha256 = pHashElement->FirstChildElement("sha256")->GetText();
		
		//printf("%s\n", sha256);
		snprintf(sql, 1023, "insert into Other_Action (other_action_id, mo_time, os_version, rule_match, type, file_desc, file_name, md5, sha256, mac_address, event_task_id,strings,stroffset) values('%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
			str, cTime, cOsName, rule, nType, cDesc, cFile, md5, sha256, Mac, EventId,"","");

		int ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
		if(ret != 0)
		{
			perror(err_msg);
			sqlite3_free(err_msg);
			//sqlite3_close(db);
		}

		pElement = pElement->NextSiblingElement("base_match");
	}/*
pElement = pElement->FirstChildElement("extend_match");
	while(pElement != NULL)
	{
		//printf("%s\n", pElement->Name());
		memset(sql, 0, sizeof(char)*1024);

		// UUID
		char str[36];
		memset(str, 0, sizeof(char)*36);
		//uuid_t uuid;
		//uuid_generate(uuid);
		//uuid_unparse(uuid, str);
		GetUUID(str, 36);
	
		const char * time = pElement->FirstChildElement("motime")->GetText();
		//printf("%s\n", time);
		const char * rule = pElement->FirstChildElement("rule_match")->GetText();
		//printf("%s\n", rule);
		const char * type = pElement->FirstChildElement("type")->GetText(); // ADWare.Badspeech APT.Malware APT.RAT Backdoor.Webshell
		int nType = 0;
		if(strstr(rule, "DWare.Badspeech") != NULL)
			nType = 4;
		
		else
			nType = 0;
		
		//printf("%s\n", type);
		const char * desc = pElement->FirstChildElement("desc")->GetText();
		char cDesc[64] = {0};
		memset(cDesc, 0, sizeof(char)*64);
		strcpy(cDesc, desc);
		StrReplace(cDesc, "'", "''");
		//printf("%s\n", desc);
		const char * file = pElement->FirstChildElement("file")->GetText();
		char cFile[1024] = {0};
		memset(cFile, 0, sizeof(char)*1024);
		strcpy(cFile, file);
		StrReplace(cFile, "'", "''");
		//printf("%s\n", file);
		const char * stroffset = pElement->FirstChildElement("offset")->GetText();
		char cOffset[20];
		memset(cOffset,0,sizeof(char)*20);
		strcpy(cOffset,stroffset);
		StrReplace(cOffset, "'", "''");
		const char * strstring = pElement->FirstChildElement("string")->GetText();
		char cstring[1024];
		memset(cstring,0,sizeof(char)*1024);
		strcpy(cstring,strstring);
		StrReplace(cstring, "'", "''");
		XMLElement* pHashElement = pElement->FirstChildElement("hash");
		const char * md5 = pHashElement->FirstChildElement("md5")->GetText();
		//printf("%s\n", md5);
		const char * sha256 = pHashElement->FirstChildElement("sha256")->GetText();
		
		//printf("%s\n", sha256);
		snprintf(sql, 1023, "insert into Other_Action (other_action_id, mo_time, os_version, rule_match, type, file_desc, file_name, md5, sha256, mac_address, event_task_id,strings,stroffset) values('%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
			str, cTime, cOsName, rule, nType, cDesc, cFile, md5, sha256, mac, EventId,cstring,cOffset);

		int ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
		if(ret != 0)
		{
			perror(err_msg);
			sqlite3_free(err_msg);
			//sqlite3_close(db);
		}

		pElement = pElement->NextSiblingElement("extend_match");
	}*/

}

// 获取日志规则
bool GetWebLogRuler(char *rulerFile, pWebRuler pRuler)
{
	if(access(rulerFile, F_OK) != 0)
	{
		perror("ruler file not found");
		return false;
	}
	if(pRuler == NULL)
	{
		perror("arg err");
		return false;
	}

	FILE *fp;
	long len;
	char *data;
	fp=fopen(rulerFile,"rb");
	if(fp == NULL)
	{
		perror("open file failed1");
		return false;
	}
	fseek(fp,0,SEEK_END);
	len = ftell(fp);
	fseek(fp,0,SEEK_SET);
	data = new char [len+1];
	fread(data,1,len,fp);
	fclose(fp);

	cJSON *root = cJSON_Parse(data);
	if(!root) {
		printf("get root faild !\n");
		return false;
	}
	cJSON *reg = cJSON_GetObjectItem(root, "regexNameMark");
	strcpy(pRuler->regex, reg->valuestring);
	//cout << "-1-" <<reg->valuestring << endl;

	cJSON *spl = cJSON_GetObjectItem(root, "logsSplit");
	strcpy(pRuler->split, spl->valuestring);
	//cout << "-" <<spl->valuestring << "-" << endl;

	cJSON *fmt = cJSON_GetObjectItem(root, "logTimeFormat");
	strcpy(pRuler->timeFmt, fmt->valuestring);
	//cout << "-3-" <<fmt->valuestring << endl;

	cJSON *sip = cJSON_GetObjectItem(root, "sipPosition");
	pRuler->ipPst = sip->valueint;
	//cout << "-4-" << sip->valueint << endl;
	
	cJSON *time = cJSON_GetObjectItem(root, "timePosition");
	int array_size = cJSON_GetArraySize(time);
	cJSON *item;
	for(int i = 0; i < array_size; i++)
	{
		item = cJSON_GetArrayItem(time, i);
		if(i == 0)
			pRuler->timePosBeg = item->valueint;
		else if(i > 0)
			pRuler->timePsoEnd = item->valueint;
		if(array_size == 1)
			pRuler->timePsoEnd = 0;
		//cout << "-5-" << item->valueint << endl;
	}

	cJSON *code = cJSON_GetObjectItem(root, "codePosition");
	pRuler->codePst = code->valueint;
	//cout << "-6-" <<code->valueint << endl;

	cJSON *byte = cJSON_GetObjectItem(root, "bytePosition");
	pRuler->bytePst = byte->valueint;
	//cout << "-7-" <<byte->valueint << endl;

	cJSON *loc = cJSON_GetObjectItem(root, "timeLocale");
	strcpy(pRuler->timeLocale, loc->valuestring);
	//cout << "-8-" <<loc->valuestring << endl;

	if(data != NULL)
	{
		delete []data;
		data = NULL;
	}
	if(root)
		cJSON_Delete(root);

	return true;
}

bool GetFileSize(const char *Filename, long *Size)
{
	bool ret = false;
	int fd = open(Filename, O_RDONLY);

	if(fd < 0)
	{
		perror("open file faild");
		return ret;
	}
	struct stat buf;
	if(fstat(fd, &buf) < 0)
	{
		close(fd);
		perror("fstat error");
		return ret;
	}
	
	if(buf.st_size > 0)
	{
		*Size = buf.st_size;
		ret = true;
	}
	close(fd);

	return ret;
}

string GetMiddleContent(string &sInput, string &sPrefix, string &sBackfix)
{
	string sRet = sInput;
	int nPos1 = 0;
	int nPos2 = 0;
	string sTmp1 = sInput;

	if(sPrefix == " \"")
	{
		bool bFind = false;
		int i = 2;
		for (;;)
		{
			nPos2 = sTmp1.find(sPrefix);
			if(nPos2 > 0)
			{
				if(sTmp1[nPos2 - 1] == '\\')
				{
					sTmp1 = sTmp1.substr(nPos2 + sPrefix.length());
					nPos1 += nPos2 + sPrefix.length();
				}
				else 
				{
					bFind = true;
					nPos1 += nPos2;
					break;
				}
			}
			else
			{
				// 日志中 http请求不再“”中， linux没有iis， 暂不考虑
			}
		}
		if (!bFind)
		{
			nPos1 = -1;//找不到
		}
	}
	else
	{
		nPos1 = sInput.find(sPrefix);
	}

	if(nPos1 >= 0)
	{
		
		string sVal1 = sInput.substr(nPos1 + sPrefix.length());
		//cout << "sval1= " << sVal1 << endl;
		if (sBackfix != "")
		{
			int nPos2 = sVal1.find(sBackfix);
			if (nPos2 > 0)
			{
				//sRet = sVal1.Left(nPos2);
				sRet = StrLeft(sVal1, nPos2);
				//cout << "sret = " << sRet << endl;
			}
		}else{
			sRet = sVal1;
		}
	}
	
	return sRet;
}

//功能:拆分输入的字符串
//参数:
//sInput：输入字符串
//sSep：分隔字符串
//bIncludeNull:包含空字符串？TRUE，包含;FALSE，不包含
//ayVecRet:拆分结果，结果参数
void SpliteStringByString(string &sInput, string &sSep, bool bIncludeNull,vector<string> &ayVecRet)
{
	string sTmp1 = sInput;

	int nPos1 = 0;

	while ((nPos1 = sTmp1.find(sSep)) >= 0)
	{
		string sVal1 = StrLeft(sTmp1, nPos1);
		if (bIncludeNull)
		{
			ayVecRet.push_back(sVal1);
		}else if (!sVal1.empty()){
			ayVecRet.push_back(sVal1);
		}
		sTmp1 = sTmp1.substr(nPos1 + sSep.length());
	}
	if(!sTmp1.empty())
	{
		ayVecRet.push_back(sTmp1);
	}
}

bool GetStdTime(pWebRuler pRuler, string TimeValue, string &sTime)
{
	sTime = "";
	bool bRet = false; 
	string TimeFmt(pRuler->timeFmt);
	
	// 删除 []  
	TimeFmt.erase(TimeFmt.begin());
	string::iterator it = TimeFmt.end();
	it--;
	TimeFmt.erase(it);

	uint uYear;
	uint uMonth;
	uint uDay;
	uint uHour;
	uint uMinite;
	uint uSeconds;

	if(TimeFmt == "dd/MMM/yyyy:HH:mm:ss Z") //apache,nginx,tomcat,jboss,weblogic
	{
		string sTimeValue = TimeValue;
		sTimeValue[11] = '/';
		sTimeValue[14] = '/';
		sTimeValue[17] = '/';
		sTimeValue[20] = '/';
		vector<string> vecRet;
		string sep("/");
		SpliteStringByString(sTimeValue, sep, false, vecRet);
		//cout << "vecsize = " << vecRet.size() << endl;
		if(vecRet.size() > 5)
		{
			uDay = atoi(vecRet[0].c_str());
			map<string, int>::iterator it = mapMonth.find(vecRet[1]);
			if(it != mapMonth.end())
			{
				uMonth = it->second;
				bRet = true;
			}

			uYear = atoi(vecRet[2].c_str());
			uHour = atoi(vecRet[3].c_str());
			uMinite = atoi(vecRet[4].c_str());
			uSeconds = atoi(vecRet[5].c_str());
		}
	}
	if(bRet)
	{
		char dTime[24] = {0};
		sprintf(dTime, "%04d-%02d-%02d %02d:%02d:%02d", uYear, uMonth, uDay, uHour, uMinite, uSeconds);
		sTime = dTime;
		//cout << "dTime = " << dTime << endl;
		//cout << "sTime = " << sTime << endl;
	}

	return bRet;
}

bool GetTimeString(string &sInput, string &sStandardTime, pWebRuler pRuler)
{
	bool bRet = false;
	sStandardTime = "";

	//cout << "sinput = " << sInput << endl;
	

	if(pRuler->timeFmt != NULL && pRuler->timeFmt[0] == '[' && pRuler->timeFmt[strlen(pRuler->timeFmt)-1] == ']')
	{
		string pre("[");
		string back("]");
		string sTimeValue = GetMiddleContent(sInput,pre, back);//sInput:假设只有一处[]字符串，并且是时间，否则会出错。
		//cout << "stiemvalue = " << sTimeValue << endl;
		bRet = GetStdTime(pRuler, sTimeValue, sStandardTime);
		if(bRet)
		{
			char dTime[36] = {0};
			sprintf(dTime, "[%s]", sTimeValue.c_str());
			string old(dTime);
			int n1 = sInput.find(old);
			int n2 = old.length();

			sInput.replace(n1, n2, "-");
			//cout << "sInput2= " << sInput << endl;
		}
	}
	else
	{
		vector<string> vec2;
		string spl(pRuler->split);
		SpliteStringByString(sInput, spl, false, vec2);
		string sTimeValue = "";
		if(pRuler->timePosBeg < vec2.size())
		{
			if(sTimeValue == "")
			{
				sTimeValue = vec2[pRuler->timePosBeg];
			}
		}
		if(pRuler->timePsoEnd != 0 && pRuler->timePsoEnd < vec2.size())
		{
			sTimeValue += spl+vec2[pRuler->timePsoEnd];
		}

		string splR = "";
		sTimeValue = GetMiddleContent(sTimeValue, spl, splR);
		bRet = GetStdTime(pRuler, sTimeValue, sStandardTime);
	}
	
	//cout << "stdtime34 = " << sStandardTime << endl;
	//cout << bRet << endl;
	return bRet;
}
char *substrend1(char *str, int n)
{
	char * substr = (char*) malloc (n+1);
	int length = strlen(str);
	if(n >= length)//若截取长度大于字符串长度，则直接截取全部字符串
	{
		strcpy(substr, str);
		return substr;
	}
	int k = 0;
	for(int i = strlen(str) - n ; i < strlen(str); i++)
	{
		substr[k++] = str[i];
	}
	substr[k] = '\0';
	return substr;
}
string GetContent(string &sInput)
{
	string sRet = sInput;
	int index =sRet.find("~~");
	
	string t=sRet.substr(index+2,sRet.length()-index+2);
	return sRet=t;
}
bool GetVectorByString(string &sInput, vector<string> &vecRet, pWebRuler pRuler, string sPre)
{
	vecRet.clear();
	char cSqlL[8] = {0};
	sprintf(cSqlL, "%s\"", pRuler->split);
	char cSqlR[8] = {0};
	sprintf(cSqlR, "\"%s", pRuler->split);
	string strSplL(cSqlL);
	string strSplR(cSqlR);

	//cout << strSplL << "----" << strSplR << endl;

	string spl = pRuler->split;

	//cout << sInput << endl;

	string sHttp = GetMiddleContent(sInput, strSplL, strSplR);
	string sHttp1=GetContent(sInput);
	//cout << "shttp1 = " << sHttp1 << endl;
	string sInputCopy = sInput;
	if (sHttp != "")
	{
		char *temp = new char[sHttp.length()+8];
		//cout << sHttp.length() << endl;
		int ct = sizeof(char) * (sHttp.length() +8);
		//cout << "ct = " << ct << endl;
		memset(temp, 0, ct);
		sprintf(temp, "\"%s\"", sHttp.c_str());
		//cout << "temp = " << temp << endl;
		string sOld(temp);
		delete []temp;
		//cout << "sOld = " << sOld << endl;
		int n1 = sInputCopy.find(sOld);

		int n2 = sOld.length();

		sInputCopy.replace(n1, n2, "-");
		if(sHttp1.length()>4000)
		{
		  string st1=sHttp1.substr(0,3000);
		//  string st2=sHttp1.substr(sHttp1.rfind("/http"),sHttp1.length()-sHttp1.rfind("/http"));
		//strcat(st1,st2);
		sHttp1=st1;	
		}
		vecRet.push_back(sHttp1);
	}

	string strR = "";
	string sStandardTime = "";
	//cout << "GetTImeSteing up " << endl;
	bool bRet1 = GetTimeString(sInputCopy, sStandardTime, pRuler); 
	//cout << "stdtime0" << endl;
	//cout << "stdtime0 = " << sStandardTime << endl;
	if(bRet1)
	{
		//cout << "stdtime1 = " << sStandardTime << endl;
		//cout << "sPre = " << sPre << endl;
		sStandardTime = GetMiddleContent(sStandardTime, sPre, strR);
		//cout << sStandardTime << endl;
		vecRet.push_back(sStandardTime);
	}

	vector<string> vecTmp1;
	SpliteStringByString(sInputCopy, spl, false, vecTmp1);

	int n1 = pRuler->ipPst;
	if(n1 < vecTmp1.size())
	{
		string sIp = vecTmp1[n1];
		sIp = GetMiddleContent(sIp, sPre, strR);
		vecRet.push_back(sIp);
	}

	int n2 = pRuler->codePst;
	if(n2 < vecTmp1.size())
	{
		vecRet.push_back(vecTmp1[n2]);
	}

	if(vecRet.size() != 4)
	{
		printf("error: %s", sInput.c_str());
	}

	return vecRet.size() == 4;
}

void WriteAttackVecToDb(sqlite3 *db, vector<string> &vt, pWebRuler pRuler, string sPre, string sAttackType, char *eventId)
{
	vector<vector<string> > vecResult;
	vector<string>::iterator it1;
	
	for(it1 = vt.begin(); it1 != vt.end(); it1++)
	{
		//cout << sPre << "---" << pRuler->timeFmt << endl;
		vector<string> vecTmp1;
		bool bRet = GetVectorByString(*it1, vecTmp1, pRuler, sPre);
		if(bRet)
		{
			vecResult.push_back(vecTmp1);
		}
	}

	// Mac
	//char mac[32] = {0};
	//GetMacAddr(mac);
char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	char *err_msg;

	vector<vector<string> >::iterator it2;
	for(it2 = vecResult.begin(); it2 != vecResult.end(); it2++)
	{
		vector<string> vec1 = *it2;
		if(vec1.size() >=4)
		{
			string sHttp = vec1[0];
			StrReplace(sHttp, "'", "''");
			string sTime = vec1[1];
			string sIp = vec1[2];
			string sCode = vec1[3];
			StrReplace(sCode, "'", "''");

			// UUID
			char str[36];
			memset(str, 0, sizeof(char)*36);

			//uuid_t uuid;
			//uuid_generate(uuid);
			//uuid_unparse(uuid, str);
			GetUUID(str, 36);

			char sql[10240] = {0};
			snprintf(sql, 10240-1, "insert into Web_Attack_Action (web_attack_action_id, attack_code, attack_ip, attack_time, http_request, http_response, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '')", 
				str, sAttackType.c_str(), sIp.c_str(), sTime.c_str(), sHttp.c_str(), sCode.c_str(), Mac, eventId);


			int ret_ok = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
			if(ret_ok != 0)
			{
				perror(err_msg);
				sqlite3_free(err_msg);

				continue;
			}

		}
	}

}
void WriteAttackVecToDb1(sqlite3 *db, vector<string> &vt, pWebRuler pRuler, string sPre, string sAttackType, char *eventId)
{
	vector<vector<string> > vecResult;
	vector<string>::iterator it1;
	
	for(it1 = vt.begin(); it1 != vt.end(); it1++)
	{
		//cout << sPre << "---" << pRuler->timeFmt << endl;
		vector<string> vecTmp1;
		bool bRet = GetVectorByString(*it1, vecTmp1, pRuler, sPre);
		if(bRet)
		{
			vecResult.push_back(vecTmp1);
		}
	}

	// Mac
	//char mac[32] = {0};
	//GetMacAddr(mac);
char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	char *err_msg;

	vector<vector<string> >::iterator it2;
	for(it2 = vecResult.begin(); it2 != vecResult.end(); it2++)
	{
		vector<string> vec1 = *it2;
		if(vec1.size() >=4)
		{
			string sHttp = vec1[0];
			StrReplace(sHttp, "'", "''");
			string sTime = vec1[1];
			string sIp = vec1[2];
			string sCode = vec1[3];
			StrReplace(sCode, "'", "''");

			// UUID
			char str[36];
			memset(str, 0, sizeof(char)*36);

			//uuid_t uuid;
			//uuid_generate(uuid);
			//uuid_unparse(uuid, str);
			GetUUID(str, 36);

			char sql[10240] = {0};
			snprintf(sql, 10240-1, "insert into scan_tool_log_action(id,scan_tool_type,scan_ip,scan_time,http_request,http_response,mac_address,event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '')", str, sAttackType.c_str(), sIp.c_str(), sTime.c_str(), sHttp.c_str(), sCode.c_str(), Mac, eventId);
				


			int ret_ok = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
			if(ret_ok != 0)
			{
				perror(err_msg);
				sqlite3_free(err_msg);

				continue;
			}

		}
	}

}
int ScantooLogToDb(const char *RstDir, pWebRuler pRuler, sqlite3 *db, char *eventId)
{

vector<pair<string, string> > vtAttackType;
	typedef pair<string, string> pairType;
	vtAttackType.push_back(pairType("watchertrack_attack_AppscanAttack.ydtxt", "Appscan"));
	vtAttackType.push_back(pairType("watchertrack_attack_AWVSAttack.ydtxt", "AWVS"));
	vtAttackType.push_back(pairType("watchertrack_attack_BabyKrokodilAttack.ydtxt", "BabyKrokodil"));
	vtAttackType.push_back(pairType("watchertrack_attack_dirbusterAttack.ydtxt", "dirbuster"));
	vtAttackType.push_back(pairType("watchertrack_attack_havijAttack.ydtxt", "havij"));
	vtAttackType.push_back(pairType("watchertrack_attack_httperfAttack.ydtxt", "httperf"));
	vtAttackType.push_back(pairType("watchertrack_attack_HTTrackAttack.ydtxt", "HTTrack"));
	vtAttackType.push_back(pairType("watchertrack_attack_hydraAttack.ydtxt", "hydra"));
	vtAttackType.push_back(pairType("watchertrack_attack_NessusAttack.ydtxt", "Nessus"));
	//vtAttackType.push_back(pairType("watchertrack_attack_Struts2Attack.ydtxt", "struts2"));
	vtAttackType.push_back(pairType("watchertrack_attack_NetsparkerAttack.ydtxt", "Netsparker"));
	vtAttackType.push_back(pairType("watchertrack_attack_NiktoAttack.ydtxt", "Nikto"));
	vtAttackType.push_back(pairType("watchertrack_attack_nmapAttack.ydtxt", "nmap"));
	vtAttackType.push_back(pairType("watchertrack_attack_owaspAttack.ydtxt", "owasp"));
	vtAttackType.push_back(pairType("watchertrack_attack_pangolinAttack.ydtxt", "pangolin"));
	//2020.11.4
	vtAttackType.push_back(pairType("watchertrack_attack_RsasAttack.ydtxt", "Rsas"));
vtAttackType.push_back(pairType("watchertrack_attack_SQLMapAttack.ydtxt", "SQLMap"));
vtAttackType.push_back(pairType("watchertrack_attack_w3afAttack.ydtxt", "w3af"));
vtAttackType.push_back(pairType("watchertrack_attack_WebinspectAttack.ydtxt", "Webinspect"));
vtAttackType.push_back(pairType("watchertrack_attack_zmeuAttack.ydtxt", "zmeu"));

	vector<pair<string, string> > vtSipPre;
	vtSipPre.push_back(pairType("AWVSAttack", "AWVSAttack~~"));
	vtSipPre.push_back(pairType("AppscanAttack", "AppscanAttack~~"));
	vtSipPre.push_back(pairType("BabyKrokodilAttack", "BabyKrokodilAttack~~"));
	vtSipPre.push_back(pairType("dirbusterAttack", "dirbusterAttack~~"));
	vtSipPre.push_back(pairType("havijAttack", "havijAttack~~"));
	vtSipPre.push_back(pairType("httperfAttack", "httperfAttack~~"));
	vtSipPre.push_back(pairType("HTTrackAttack", "HTTrackAttack~~"));
	vtSipPre.push_back(pairType("hydraAttack", "hydraAttack~~"));
	vtSipPre.push_back(pairType("NessusAttack", "NessusAttack~~"));
	//vtSipPre.push_back(pairType("Struts2Attack", "Struts2Attack~~"));
	vtSipPre.push_back(pairType("NetsparkerAttack", "NetsparkerAttack~~"));
	vtSipPre.push_back(pairType("NiktoAttack", "NiktoAttack~~"));
	vtSipPre.push_back(pairType("nmapAttack","nmapAttack~~"));
	vtSipPre.push_back(pairType("owaspAttack","owaspAttack~~"));
	vtSipPre.push_back(pairType("pangolinAttack","pangolinAttack~~"));
	//2020.11.4
	vtSipPre.push_back(pairType("RsasAttack","RsasAttack~~"));
	vtSipPre.push_back(pairType("SQLMapAttack","SQLMapAttack~~"));
	vtSipPre.push_back(pairType("w3afAttack","w3afAttack~~"));
	vtSipPre.push_back(pairType("WebinspectAttack","WebinspectAttack~~"));
	vtSipPre.push_back(pairType("zmeuAttack","zmeuAttack~~"));
	string Dir(RstDir);
	string AttackType;
	vector<pair<string, string> > ::iterator it, it2;
	for(it = vtAttackType.begin(); it != vtAttackType.end(); it++)
	{
		//cout << (*it).first << endl;
		string strFile = Dir + (*it).first;
		AttackType = it->second;
		// 日志内容前缀：
		string sipPre;
		for(it2 = vtSipPre.begin(); it2 != vtSipPre.end(); it2++)
		{
			int n = strFile.find((*it2).first.c_str());
			if(n > 0)
			{
				sipPre = (*it2).second.c_str();
				break;
			}
		}

		long size;
		bool bfile = GetFileSize(strFile.c_str(), &size);
		if(!bfile)
		{
			continue;
		}

		//cout << "size" << size << endl;

		FILE *fp;
		fp = fopen(strFile.c_str(), "r");
		if(!fp)
			continue;
		
		vector<string> vecFileContent;
		int nRowCt = 1;
		char ch1[BUFFERSIZE] = {0};
		string strRow = "";
		bool bIsFullRow = false;
		while(fgets(ch1, BUFFERSIZE-1, fp) != NULL)
		{
			//cout << ch1 << endl;
			int n = strlen(ch1);
			if(n >= 1 && n < BUFFERSIZE && ch1[n - 1] == '\n')
			{
				ch1[n-1] = '\0';
				strRow += string(ch1);
				++nRowCt;
				vecFileContent.push_back(strRow);
				strRow = "";
			}
			else
			{
				strRow += string(ch1);
				memset(ch1, 0, BUFFERSIZE * sizeof(char));
				continue;
			}
			memset(ch1, 0, BUFFERSIZE * sizeof(char));

			if(nRowCt > scnRow)
			{
				//cout << "size1 = " << vecFileContent.size() << endl;
				//处理日志
				WriteAttackVecToDb1(db, vecFileContent, pRuler, sipPre, AttackType, eventId);
				nRowCt = 1;
				vecFileContent.clear();
			}

		}
		if(vecFileContent.size() > 0)
		{
			//cout << "size2 = " << vecFileContent.size() << endl;

			// 处理日志
			WriteAttackVecToDb1(db, vecFileContent, pRuler, sipPre, AttackType, eventId);
			vecFileContent.clear();
		}

		fclose(fp);
	}
	
	return 0;
}
int LogToDb(const char *RstDir, pWebRuler pRuler, sqlite3 *db, char *eventId)
{
	vector<pair<string, string> > vtAttackType;
	typedef pair<string, string> pairType;
	vtAttackType.push_back(pairType("watchertrack_attack_FileIncludeAttack.ydtxt", "file_include"));
	vtAttackType.push_back(pairType("watchertrack_attack_HttpCRLFAttack.ydtxt", "http_crlf"));
	vtAttackType.push_back(pairType("watchertrack_attack_IncHTTPAttack.ydtxt", "domain"));
	vtAttackType.push_back(pairType("watchertrack_attack_JavaouinStreamAttack.ydtxt", "java_ouin_stream"));
	vtAttackType.push_back(pairType("watchertrack_attack_PasswdAttackAttack.ydtxt", "passwd_attack"));
	vtAttackType.push_back(pairType("watchertrack_attack_ScanRobotsAttack.ydtxt", "scan_robots"));
	vtAttackType.push_back(pairType("watchertrack_attack_SensitiveFileAttack.ydtxt", "sensitive_file"));
	vtAttackType.push_back(pairType("watchertrack_attack_ShellShockAttack.ydtxt", "shell_shock"));
	vtAttackType.push_back(pairType("watchertrack_attack_SQLInjectionAttack.ydtxt", "sql_injection"));
	//vtAttackType.push_back(pairType("watchertrack_attack_Struts2Attack.ydtxt", "struts2"));
	vtAttackType.push_back(pairType("watchertrack_attack_WebShellAttack.ydtxt", "webshell"));
	vtAttackType.push_back(pairType("watchertrack_attack_XSSAttack.ydtxt", "xss"));
	vtAttackType.push_back(pairType("watchertrack_attack_Struts2RemoteCommandExeAttack.ydtxt", "struts2_remote_command_exe"));
	vtAttackType.push_back(pairType("watchertrack_attack_Struts2AttackAttack.ydtxt", "struts2_attack"));
	vtAttackType.push_back(pairType("watchertrack_attack_urlJumpAttack.ydtxt", "urljump"));
	//2020.11.4
	vtAttackType.push_back(pairType("watchertrack_attack_CommandExecutionAttack.ydtxt", "command_execution"));

	vector<pair<string, string> > vtSipPre;
	vtSipPre.push_back(pairType("FileIncludeAttack", "FileIncludeAttack~~"));
	vtSipPre.push_back(pairType("HttpCRLFAttack", "HttpCRLFAttack~~"));
	vtSipPre.push_back(pairType("IncHTTPAttack", "IncHTTPAttack~~"));
	vtSipPre.push_back(pairType("JavaouinStreamAttack", "JavaouinStreamAttack~~"));
	vtSipPre.push_back(pairType("PasswdAttackAttack", "PasswdAttackAttack~~"));
	vtSipPre.push_back(pairType("ScanRobotsAttack", "ScanRobotsAttack~~"));
	vtSipPre.push_back(pairType("SensitiveFileAttack", "SensitiveFileAttack~~"));
	vtSipPre.push_back(pairType("ShellShockAttack", "ShellShockAttack~~"));
	vtSipPre.push_back(pairType("SQLInjectionAttack", "SQLInjectionAttack~~"));
	//vtSipPre.push_back(pairType("Struts2Attack", "Struts2Attack~~"));
	vtSipPre.push_back(pairType("WebShellAttack", "WebShellAttack~~"));
	vtSipPre.push_back(pairType("XSSAttack", "XSSAttack~~"));
	vtSipPre.push_back(pairType("Struts2RemoteCommandExeAttack","Struts2RemoteCommandExeAttack~~"));
	vtSipPre.push_back(pairType("Struts2AttackAttack","Struts2AttackAttack~~"));
	vtSipPre.push_back(pairType("urlJump","urlJumpAttack~~"));
	//2020.11.4
	vtSipPre.push_back(pairType("CommandExecution","CommandExecutionAttack~~"));
	string Dir(RstDir);
	string AttackType;
	vector<pair<string, string> > ::iterator it, it2;
	for(it = vtAttackType.begin(); it != vtAttackType.end(); it++)
	{
		//cout << (*it).first << endl;
		string strFile = Dir + (*it).first;
		AttackType = it->second;
		// 日志内容前缀：
		string sipPre;
		for(it2 = vtSipPre.begin(); it2 != vtSipPre.end(); it2++)
		{
			int n = strFile.find((*it2).first.c_str());
			if(n > 0)
			{
				sipPre = (*it2).second.c_str();
				break;
			}
		}

		long size;
		bool bfile = GetFileSize(strFile.c_str(), &size);
		if(!bfile)
		{
			continue;
		}

		//cout << "size" << size << endl;

		FILE *fp;
		fp = fopen(strFile.c_str(), "r");
		if(!fp)
			continue;
		
		vector<string> vecFileContent;
		int nRowCt = 1;
		char ch1[BUFFERSIZE] = {0};
		string strRow = "";
		bool bIsFullRow = false;
		while(fgets(ch1, BUFFERSIZE-1, fp) != NULL)
		{
			//cout << ch1 << endl;
			int n = strlen(ch1);
			if(n >= 1 && n < BUFFERSIZE && ch1[n - 1] == '\n')
			{
				ch1[n-1] = '\0';
				strRow += string(ch1);
				++nRowCt;
				vecFileContent.push_back(strRow);
				strRow = "";
			}
			else
			{
				strRow += string(ch1);
				memset(ch1, 0, BUFFERSIZE * sizeof(char));
				continue;
			}
			memset(ch1, 0, BUFFERSIZE * sizeof(char));

			if(nRowCt > scnRow)
			{
				//cout << "size1 = " << vecFileContent.size() << endl;
				//处理日志
				WriteAttackVecToDb(db, vecFileContent, pRuler, sipPre, AttackType, eventId);
				nRowCt = 1;
				vecFileContent.clear();
			}

		}
		if(vecFileContent.size() > 0)
		{
			//cout << "size2 = " << vecFileContent.size() << endl;

			// 处理日志
			WriteAttackVecToDb(db, vecFileContent, pRuler, sipPre, AttackType, eventId);
			vecFileContent.clear();
		}

		fclose(fp);
	}
	
	return 0;
}

// 解析json文件
int ParseJsonFile(sqlite3 *db, char *RstDir, char *eventId)
{
	string strDir = RstDir;
	char dir[PATH_MAX] = {0};
	char JsonFile[PATH_MAX] = {0};
	strcpy(dir, RstDir);
	strcpy(JsonFile, RstDir);

	strcat(JsonFile, "watchertrack_attack.ydjson");
	FILE *fp;
	fp=fopen(JsonFile,"rb");
	if(fp == NULL)
	{
		perror("Open file failed");
		return -1;
	}

	long len;
	char *data;
	fseek(fp, 0, SEEK_END);
	len = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	data = new char [len+1];
	fread(data, 1, len, fp);
	fclose(fp);

	cJSON *root;
	root = cJSON_Parse(data);

	cJSON *ability = cJSON_GetObjectItem(root, "ability");
	if(!ability)
	{
		perror("error01");
		return -2;
	}
	char *cAbilty = ability->valuestring;

	cJSON *attackCount = cJSON_GetObjectItem(root, "attackCount");
	if(!attackCount)
	{
		perror("error02");
		return -3;
	}
	uint64_t nAttackCount = attackCount->valueint;

	cJSON *logCount = cJSON_GetObjectItem(root, "logCount");
	if(!logCount)
	{
		perror("error03");
		return -4;
	}
	uint64_t nLogCount = logCount->valueint;

	cJSON *logPath = cJSON_GetObjectItem(root, "logPath");
	if(!logPath)
	{
		perror("error04");
		return -5;
	}
	char *cLogPath = logPath->valuestring;
	StrReplace(cLogPath, "'", "''");

	cJSON *logType = cJSON_GetObjectItem(root, "logType");
	if(!logType)
	{
		perror("error05");
		return -6;
	}
	char *cLogType = logType->valuestring;

	cJSON *sipCount = cJSON_GetObjectItem(root, "sipCount");
	if(!sipCount)
	{
		perror("error06");
		return -7;
	}

	cJSON *ch = sipCount->child;
	string ipCount = "";
	char temp[36] = {0};
	while(ch != NULL)
	{
		//cout << ch->string << endl;
		//cout << ch->valueint << endl;
		char *Ip = ch->string;
		int cnt = ch->valueint;
		memset(temp, 0, sizeof(char)*36);
		//"10.1.29.157": 26,"10.1.29.3": 17,"10.10.247.65": 5,"10.112.130.254": 8
		if(ipCount == "")
		{
			sprintf(temp, "\"%s\": %d", Ip, cnt);
			ipCount += temp;
		}
		else
		{
			sprintf(temp, ",\"%s\": %d", Ip, cnt);
			ipCount += temp;
		}
		ch = ch->next;
	}
	//cout << ipCount << endl;

	cJSON *typeCount = cJSON_GetObjectItem(root, "typeCount");
	if(!typeCount)
	{
		perror("error07");
		return -8;
	}

	cJSON *chJson = typeCount->child;

	unsigned int FileInclude = 0;
	unsigned int HttpCRLF = 0;
	unsigned int JavaouinStream = 0;
	unsigned int Passwd = 0;
	unsigned int ScanRobots = 0;
	uint64_t SensitiveFile = 0;
	unsigned int ShellShock = 0;
	unsigned int SQLInjection = 0;
	unsigned int Struts2 = 0;
	unsigned int WebShell = 0;
	unsigned int XSS = 0;
	unsigned int Struts2comd=0;
	unsigned int Struts2Attack=0;
	unsigned int urljump=0;
	unsigned int CommandExecution=0;

	// xss http_crlf shell_shock struts2 webshell sql_injection
	while(chJson != NULL)
	{
		//cout << chJson->string << "=" << chJson->valueint << endl;
		if(strcmp(chJson->string, "FileInclude") == 0)
			FileInclude = chJson->valueint;
		if(strcmp(chJson->string, "HttpCRLF") == 0)
			HttpCRLF = chJson->valueint;
		if(strcmp(chJson->string, "JavaouinStream") == 0)
			JavaouinStream = chJson->valueint;
		if(strcmp(chJson->string, "Passwd") == 0)
			Passwd = chJson->valueint;
		if(strcmp(chJson->string, "ScanRobots") == 0)
			ScanRobots = chJson->valueint;
		if(strcmp(chJson->string, "SensitiveFile") == 0)
			SensitiveFile = chJson->valueint;
		if(strcmp(chJson->string, "ShellShock") == 0)
			ShellShock = chJson->valueint;
		if(strcmp(chJson->string, "SQLInjection") == 0)
			SQLInjection = chJson->valueint;
		if(strcmp(chJson->string, "Struts2") == 0)
			Struts2 = chJson->valueint;
		if(strcmp(chJson->string, "WebShell") == 0)
			WebShell = chJson->valueint;
		if(strcmp(chJson->string, "XSS") == 0)
			XSS = chJson->valueint;
		if(strcmp(chJson->string, "Struts2Attack") == 0)
			Struts2Attack = chJson->valueint;
		if(strcmp(chJson->string, "Struts2RemoteCommandExe") == 0)
			Struts2comd = chJson->valueint;
		if(strcmp(chJson->string, "urljump") == 0)
			urljump = chJson->valueint;
			//2020.11.4
		if(strcmp(chJson->string,"CommandExecution"))
			CommandExecution=chJson->valueint;
		chJson = chJson->next;
	}
//cout<<"tongjirizhi"<<Struts2comd<<endl;
//cout<<"tongjirizhi"<<Struts2Attack<<endl;
	string WebTool = "";
	vector<pair<string, string> >::iterator it;
	for(it = vAttackToolType.begin(); it != vAttackToolType.end(); it++)
	{
		string strFile = strDir + (*it).first;
		long size;
		if(GetFileSize(strFile.c_str(), &size))
		{
			if(WebTool == "")
			{
				WebTool += (*it).second;
			}
			else
			{
				WebTool += "," + (*it).second;
			}
		}
	}

	// UUID
	char str[36];
	memset(str, 0, sizeof(char)*36);
	//uuid_t uuid;
	//uuid_generate(uuid);
	//uuid_unparse(uuid, str);
	GetUUID(str, 36);

	// Mac
	//char mac[32] = {0};
	//GetMacAddr(mac);
	char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	char *err_msg;
	char sql[5120] = {0};
	snprintf(sql, 5120-1, "insert into watchertrack_attack_record (id, extend_rule, ability, attack_count, file_include, java_ouin_stream, log_count, log_path, log_type, passwd_attack, scan_robots, sensitive_file, sipcount, sql_injection, webshell, struts2, shell_shock, http_crlf, xss, web_hack_tool, mac_address, event_task_id,struts2_remote_command_exe,struts2_attack,urljump,command_execution) values('%s', '0', '%s', '%lu', '%d', '%d', '%lu', '%s', '%s', '%d', '%d', '%lu', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%s', '%s','%d', '%d','%d','%d')", 
		str, cAbilty, nAttackCount, FileInclude, JavaouinStream, nLogCount, cLogPath, cLogType, Passwd, ScanRobots, SensitiveFile, ipCount.c_str(), SQLInjection, WebShell, Struts2, ShellShock, HttpCRLF,
			XSS, WebTool.c_str(), Mac, eventId,Struts2comd,Struts2Attack,urljump,CommandExecution);
	//cout<<"tongjirizhi"<<sql<<endl;
	int ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
	if(ret != 0)
	{
		perror(err_msg);
		sqlite3_free(err_msg);
	}

	delete []data;
	cJSON_Delete(root);

	return 0;
}

// Web日志结果入库
bool WebLogResultToDb(sqlite3 *db, const char *RstDir, char *EventId)
{
#ifdef _DEBUG_
	char rDir[1024] = "/home/yl/Src/build/ThreatDetectionSystem/result/temp/result2/1/";
#else
	char rDir[PATH_MAX] = {0};
	strcpy(rDir, RstDir);
#endif
	strcat(rDir, "watchertrack_attack.ydjson");
	if(access(rDir, F_OK) < 0)
	{
		perror("file not found!");
		return false;
	}
	int type = GetWebType(rDir);

	char ruler[PATH_MAX] = "./WebEngine/watchertrack/conf/";

	switch(type)
	{
		case 1:
		{
			strcat(ruler, "apache.json");
			break;
		}
		case 2:
		{
			strcat(ruler, "tomcat.json");
			break;
		}
		case 3:
		{
			strcat(ruler, "nginx.json");
			break;
		}
		case 4:
		{
			strcat(ruler, "jboss.json");
			break;
		}
		case 5:
		{
			strcat(ruler, "weblogic.json");
			break;
		}
		default:
		{

			break;
		}
	}

	WebRuler Ruler;
	memset(&Ruler, 0, sizeof(WebRuler));

	GetWebLogRuler(ruler, &Ruler);

	sqlite3_exec(db,"begin;",0,0,0);

	LogToDb(RstDir, &Ruler, db, EventId);
	sqlite3_exec(db,"commit;",0,0,0);
	sqlite3_exec(db,"begin;",0,0,0);

	ScantooLogToDb(RstDir, &Ruler, db, EventId);
	sqlite3_exec(db,"commit;",0,0,0);
	// 解析watchertrack_attack.json文件并入库
	char dir[PATH_MAX] = {0};
	strcpy(dir, RstDir);
	ParseJsonFile(db, dir, EventId);

	return true;
}

//resultPath=采集工具/采集结果/mac地址
bool WebResultToDb(sqlite3 *db, char *resultPath, char *EventId)
{
	DIR 	*pDir;  
	struct 	dirent *ent;
	struct stat statbuf;
	vector<string> vt_rst;
	vector<string> vt_xml;  // 存放xml文件名(web文件 结果)
	vector<string> vt_json; // 存放结果所在文件夹名,因为日志结果有多个文件(web日志 结果)
	vector<string>::iterator it;

	char WebPath[256];
	memset(WebPath, 0, sizeof(WebPath));
	snprintf(WebPath, 256-1, "%s/WebAttackAction", resultPath);

	//pDir=opendir("./ThreatDetectionSystem/result");
	pDir=opendir(WebPath);
	if(pDir == NULL)
		return false;
	
	cout << "open dir success" << endl;
	
	// 获取所有结果文件夹的名字
	while((ent=readdir(pDir))!=NULL) 
	{
		if(ent->d_type == DT_DIR)
		{
			if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
				continue;
			char * fileName = ent->d_name;
			//cout << fileName << endl;
			string str(fileName);
			vt_rst.push_back(str);
		}
	}

/*
	char cCmd[256];
	memset(cCmd, 0, sizeof(cCmd));
	snprintf(cCmd, 256-1, " rm -r %s/temp", WebPath);

	// 删除存放结果的文件夹
	//system("rm -r ./ThreatDetectionSystem/result/temp");
	system(cCmd);
	// 创建空文件夹
	memset(cCmd, 0, sizeof(cCmd));
	snprintf(cCmd, 256-1, " mkdir -p %s/temp", WebPath);
	//system("mkdir ./ThreatDetectionSystem/result/temp");
	system(cCmd);

	// 解压所有压缩包
	int i = 1;
	char unZipCom[PATH_MAX] = {0};
	char XmlFile[PATH_MAX] = {0};
	char JsonFile[PATH_MAX] = {0};
	//cout << vt_zip.size() << endl;
	for(it = vt_zip.begin(); it != vt_zip.end(); it++)
	{
		memset(unZipCom, 0, sizeof(char)*PATH_MAX);
		//sprintf(unZipCom, "unzip -o ./ThreatDetectionSystem/result/%s -d ./ThreatDetectionSystem/result/temp/result%d", (*it).c_str(), i);
		sprintf(unZipCom, "unzip -o %s/%s -d %s/temp/result%d", WebPath, (*it).c_str(), WebPath, i);
		system(unZipCom);
*/
	for(it = vt_rst.begin(); it != vt_rst.end(); it++)
	{
		char XmlFile[PATH_MAX] = {0};
		char JsonFile[PATH_MAX] = {0};

		//watchertrack_attack.json
		memset(XmlFile, 0, sizeof(char)*PATH_MAX);
		sprintf(XmlFile, "%s/%s/watcherscan_file.ydxml", WebPath, it->c_str());
		//cout << "xml文件名： " << XmlFile << endl;
		memset(JsonFile, 0, sizeof(char)*PATH_MAX);
		sprintf(JsonFile, "%s/%s/watchertrack_attack.ydjson", WebPath, it->c_str());
		if(access(XmlFile, F_OK) == 0)  // xml文件存在， 说明是文件采集结果
		{
			//cout << "xml文件存在" << endl;
			string str(XmlFile);
			vt_xml.push_back(str);
		}
		if(access(JsonFile, F_OK) == 0) // json文件存在， 说明是日志采集结果
		{

			char dir[PATH_MAX] = {0};
			sprintf(dir, "%s/%s/", WebPath, it->c_str());
			string str(dir);
			vt_json.push_back(str);
		}
		else
		{
	
		}
	}

	for(it = vt_xml.begin(); it != vt_xml.end(); it++)
	{
		cout << "开始获取Web文件结果" << endl;
		//WebFileResultToDb(db, (*it).c_str(), EventId);
	}

	for(it = vt_json.begin(); it != vt_json.end(); it++)
	{
		//cout << "开始获取日志结果:" << (*it).c_str() << endl;
		WebLogResultToDb(db, (*it).c_str(), EventId);
	}

	return true;
}

bool virResultToDb(sqlite3 *db, char *ResultPath, char *eventId)
{
	cJSON *js_list;
	int arr_size;
	int i = 0;
	cJSON * item, *it, *jsonVir, *jsonFile;
	char *p = NULL;
	char sql[2048] = {0};
	char Mac[100] = {0};
	int ret;
	char *err_msg;

#ifdef _DEBUG_
	char * filename0 = "/home/yl/Src/build/watcherAntivirus/result/ret";
#else
	//char * filename0 = "./watcherAntivirus/result/ret";
	char filename0[256];
	memset(filename0, 0, sizeof(filename0));
	snprintf(filename0, 256-1, "%s/virus/ret", ResultPath);
#endif


	if(access(filename0, F_OK) != 0)
	{
		cout << "virus result is not existed!" << endl;
		return false;
	}

	FILE *fp;
	long len;
	char *data;
	fp=fopen(filename0,"rb");
	if(fp == NULL)
	{
		perror("open file failed2");
		return false;
	}
	fseek(fp,0,SEEK_END);
	len = ftell(fp);
	fseek(fp,0,SEEK_SET);
	data = new char [len+1];
	fread(data,1,len,fp);
	fclose(fp);

	cJSON *json;
	char *out;
	json = cJSON_Parse(data);
	if(!json)
	{
		perror("Json is null 1");
		goto End;
	}

	// Mac
	GetMacAddr(Mac);
	//char mac[100] = {0};
	//memset(mac, 0, sizeof(mac));
	//GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char mac[100];
	memset(mac,0,sizeof(mac));
	strcat(mac,Mac);
	strcat(mac,"~~");
	strcat(mac,cIp);
	js_list = cJSON_GetObjectItem(json, "infected_files");
	arr_size = cJSON_GetArraySize(js_list);
	for(i = 0; i < arr_size; i++)
	{
		item = cJSON_GetArrayItem(js_list, i);
		if(!item)
		{
			perror("get element failed");
			goto End;
		}
		p = cJSON_PrintUnformatted(item);
		it = cJSON_Parse(p);
		if(p != NULL)
			free(p);
		if(!it)
			continue;
		
		// UUID
		char cUUID[36];
		memset(cUUID, 0, sizeof(char)*36);
		//uuid_t uuid;
		//uuid_generate(uuid);
		//uuid_unparse(uuid, cUUID);
		GetUUID(cUUID, 36);
		
		// 病毒类型
		jsonVir = cJSON_GetObjectItem(it, "virusname");
		char virName[1024] = {0};
		memset(virName, 0, sizeof(char)*1024);
		strncpy(virName, jsonVir->valuestring, 1023);
		StrReplace(virName, "'", "''");
		
		// 文件名
		jsonFile = cJSON_GetObjectItem(it, "filename");
		char fileName[1024] = {0};
		memset(fileName, 0, sizeof(char)*1024);
		strncpy(fileName, jsonFile->valuestring, 1023);
		StrReplace(fileName, "'", "''");
	
		memset(sql, 0, sizeof(char)*2048);
		snprintf(sql, 2047, "insert into Virus_Data (virus_data_id, file_name, virus_type, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s')", 
			cUUID, fileName, virName, mac, eventId);
		
		ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
		if(ret != 0)
		{
			perror(err_msg);
			sqlite3_free(err_msg);
		}
	}

End:
	if(data != NULL)
		delete []data;
	if(json)
		cJSON_Delete(json);

}

bool GetTableCount(sqlite3 *db, char *table)
{
	if(db == NULL || table == NULL)
		return false;
	
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	char sql[128];
	memset(sql, 0, sizeof(sql));
	snprintf(sql, 128-1, "select count(*) from %s", table);
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		int count = atoi(dbResult[index]);
		sqlite3_free_table(dbResult);
		if(count > 0)
			return true;
		else
			return false; 
	}
	
	sqlite3_free(errMsg);
	return false;
}

void GetAttackIPandTime(sqlite3 *db, char *Mac, vector<pAttackIP>&vtAttackIP, char *eventId)
{
	if(db == NULL)
		return;

	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	vector<string> vtIp;
	vector<string>::iterator it;
	//vector<pAttackIP> vtAttackIP;
	vector<pAttackIP>::iterator it2;
	char *cSql = "select distinct attack_ip from Web_Attack_Action";//attack_time
	ret = sqlite3_get_table(db, cSql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				string ip(dbResult[index]);
				if(ip.size() > 7)
					vtIp.push_back(ip);

				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	char Sql[512] = {0};
	char Sql2[1024] = {0};
	for(it = vtIp.begin(); it != vtIp.end(); it++)
	{
		memset(Sql, 0, sizeof(Sql));
		snprintf(Sql, 512-1, "select attack_time from Web_Attack_Action where attack_ip = '%s' order by 1", (*it).c_str());
		ret = sqlite3_get_table(db, Sql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			string minTime(dbResult[nColumn]);  // 结果第一个
			string maxTime;
			if(nRow >1)
				maxTime = dbResult[nRow-1];   // 结果最后一个
			else
				maxTime = minTime;
			
			pAttackIP pAtIp = new AttackIp;
			memset(pAtIp, 0, sizeof(AttackIp));
			strncpy(pAtIp->ip, (*it).c_str(), 35);
			strncpy(pAtIp->firstTime, minTime.c_str(), 35);
			strncpy(pAtIp->lastTime, maxTime.c_str(), 35);
			vtAttackIP.push_back(pAtIp);

			//memset(Sql2, 0, sizeof(Sql2));
			//snprintf(Sql2, 1024-1, "insert into ");
			//ret = sqlite3_exec(db, Sql2, NULL, NULL, &errMsg);
			//if(ret != SQLITE_OK)
			//{
			//	cout << errMsg << endl;
			//	sqlite3_free(errMsg);
			//}

			sqlite3_free_table(dbResult); // 释放结果
		}
		if(errMsg != NULL)
		{
			cout << errMsg << endl;
			sqlite3_free(errMsg);
		}

	}

	char cSql3[1024];
	char cUUID[36];
	for(it2 = vtAttackIP.begin(); it2 != vtAttackIP.end(); it2++)
	{
		memset(cSql3, 0, sizeof(cSql3));
		// UUID
		memset(cUUID, 0, sizeof(char)*36);
		//uuid_t uuid;
		//uuid_generate(uuid);
		//uuid_unparse(uuid, cUUID);
		GetUUID(cUUID, 36);

		snprintf(cSql3, 1024-1, "insert into Source_Ip_Analysis (source_ip_analysis_id, ip_address, recent_attack_time, attack_time_begin, attack_time_end, ip_library_id, ip_section, area, operator, country_phone_num, timezone, longitude_and_latitude, administrative_region_code, postcode, mac_address, ip_source, deflag, event_task_id) values('%s', '%s', '', '%s', '%s', '', '', '', '', '', '', '', '', '', '%s', '%s', '', '%s')", 
			cUUID, (*it2)->ip, (*it2)->firstTime, (*it2)->lastTime, Mac, "0", eventId);
		int ret = sqlite3_exec(db, cSql3, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			perror(errMsg);
			cout << cSql3 << endl;
			sqlite3_free(errMsg);
		}
	}

 /*   for(it2 = vtAttackIP.begin(); it2 != vtAttackIP.end(); it2++)
	{
		if(*it2 != NULL)
		{
			delete *it2;
			*it2 = NULL;
		}
	}
	vtAttackIP.clear();*/
	
}

void SuspiciousFile(sqlite3 *db, char *Mac, vector<pAttackIP>&vtAttackIP, char *eventId)
{
	if(db == NULL || vtAttackIP.size() == 0)
		return;
	
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	vector<pAttackIP>::iterator it;

	char *fileName = NULL;
	char *uid = NULL;
	char *gid = NULL;
	char *size = NULL;
	char *atime = NULL;
	char *mtime = NULL;
	char *ctime = NULL;
	char ip[1024] = {0};
	char cUUID[36] = {0};
	char cSql[1024] = {0};
	char * cSql1 = "select * from Linux_All_File";
	ret = sqlite3_get_table(db, cSql1, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				if(j == 1)
					fileName = dbResult[index];
				else if(j == 2)
					uid = dbResult[index];
				else if (j == 3)
					gid = dbResult[index];
				else if(j == 4)
					size = dbResult[index];
				else if(j == 5)
					atime = dbResult[index];
				else if(j == 6)
					mtime = dbResult[index];
				else if(j == 7)
					ctime = dbResult[index];
				index++;
			}
			memset(ip, 0, sizeof(ip));
			for(it = vtAttackIP.begin(); it != vtAttackIP.end(); it++)
			{
				if(strcmp(mtime,(*it)->firstTime) >= 0 && strcmp(mtime, (*it)->lastTime) <= 0)
				{
					strcat(ip, (*it)->ip);
				}
			}
			if(strlen(ip) > 0)
			{
				// UUID
				memset(cUUID, 0, sizeof(char)*36);
				//uuid_t uuid;
				//uuid_generate(uuid);
				//uuid_unparse(uuid, cUUID);
				GetUUID(cUUID, 36);

				memset(cSql, 0, sizeof(cSql));
				snprintf(cSql, 1024-1, "insert into Linux_File (id, file_name, uid, gid, size, st_atime, st_mtime, st_ctime, sus_ip_id, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", 
					cUUID, fileName, uid, gid, size, atime, mtime, ctime, ip, Mac, eventId);
				ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
				if(ret != SQLITE_OK)
				{
					perror(errMsg);
					sqlite3_free(errMsg);
				}
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}

}

void UserInfoAndToDB(sqlite3 *db, char *Mac, char *eventId)
{
	system("cat /etc/passwd > pswd");

	char *filename = "./pswd";

    FILE *fp = NULL;
    fp = fopen(filename, "r");
    if(fp == NULL)
    {
        perror("open file failed");
        return;
    }

	char user[256];
	char passWd[256];
	char uid[16];
	char gid[16];
	char user2[256];
	char home[256];
	char shell[256];

	char sql[1024];
	char *err_msg = NULL;
	char cUUID[36];
    char buf[1024];
    int nItem = 0;
    char cField[128];
    int n = 0;
    memset(cField, 0, sizeof(cField));
    int len = 0;
    memset(buf, 0, sizeof(buf));
    while(fgets(buf, 1024-1, fp) != NULL)
    {
        len = strlen(buf);
        for(int i = 0; i < len; i++)
        {
            if(buf[i] != ':' && buf[i] != '\n')
            {
                cField[n] = buf[i];
                n++;
            }
            else
            {
                cField[n] = '\0';
                switch(nItem)
                {
                    case 0:		// 登录名
                    {
						memset(user, 0, sizeof(user));
						strncpy(user, cField, 256-1);
						//cout << "登录名： " << user << endl;
						break;
                    }
					case 1:		// 密码
					{
						memset(passWd, 0, sizeof(passWd));
						strncpy(passWd, cField, 256-1);
						//cout << "密码： " << passWd << endl;
						break;	
					}
					case 2:		// uid
					{
						memset(uid, 0, sizeof(uid));
						strncpy(uid, cField, 16-1);
						//cout << "uid： " << uid << endl;
						break;
					}
					case 3:		// gid
					{
						memset(gid, 0, sizeof(gid));
						strncpy(gid, cField, 16-1);
						//cout << "gid： " << gid << endl;
						break;
					}
					case 4:		// 用户名
					{
						memset(user2, 0, sizeof(user2));
						strncpy(user2, cField, 256-1);
						//cout << "user2： " << user2 << endl;
						break;
					}
					case 5:		// 家目录
					{
                        memset(home, 0, sizeof(home));
						strncpy(home, cField, 256-1);
						//cout << "家目录： " << home << endl;
						break;
					}
					case 6:		// 登录使用的shell
					{
                        memset(shell, 0, sizeof(shell));
						strncpy(shell, cField, 256-1);
						//cout << "shell： " << shell << endl;
						break;
					}
                }
				nItem++;
				memset(cField, 0, sizeof(cField));
				n = 0;
            }
        }
        memset(sql, 0, sizeof(sql));

		// UUID
        memset(cUUID, 0, sizeof(char)*36);
        //uuid_t uuid;
        //uuid_generate(uuid);
        //uuid_unparse(uuid, cUUID);
		GetUUID(cUUID, 36);

		StrReplace(user, "'", "''");
		StrReplace(passWd, "'", "''");
		StrReplace(user2, "'", "''");
		StrReplace(home, "'", "''");
		StrReplace(shell, "'", "''");

		snprintf(sql, 1024-1, "insert into Linux_User_Info (id, login_name, passwd, uid, gid, user_name, home_directory, shell, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )", 
			cUUID, user, passWd, uid, gid, user2, home, shell, Mac, eventId);
		int ret = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
    	if(ret != SQLITE_OK)
    	{
            perror(err_msg);
            sqlite3_free(err_msg);
        }

        nItem = 0;
        memset(buf, 0, sizeof(buf));
    }

	fclose(fp);
	system("rm pswd");

}

int updateUUID(sqlite3* db)
{
	if(db == NULL)
		return -1;
	char uuid[36];
	memset(uuid, 0, sizeof(uuid));
	GetUUID(uuid, sizeof(uuid));

	char *errMsg = NULL;
	char sql[128];
	memset(sql, 0, sizeof(sql));
	snprintf(sql, 128-1, "update IsUsed set UUID = '%s'", uuid);
	int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		perror("update isUsed failed");
		sqlite3_free(errMsg);
		return -2;
	}

	return 0;
}
/*
void GetAttackInfo(sqlite3* db, char *Mac, char *eventId)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char ** dbResult1 = NULL;
	int nRow1, nColumn1;
	int i1, j1, index1;
	char * errMsg = NULL;

	char Sql[1024];
	char Uid[36];
	char cSql[1024];
	char *host_ip = NULL;
	char *strCode=NULL;
	
	vector<string> vtCode;
	vector<string>::iterator it;
	vector<string>::iterator it2;
	vector<string> vtsinIP;
	vector<string> v_Time;
	
	memset(cSql,0,1024);
		//11.4 get host_ip
	snprintf(Sql, 1024-1,"select host_ip from Pc_Account where mac_address='%s'",Mac);

	ret = sqlite3_get_table(db, cSql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
        {
			
			host_ip=dbResult[index];
			cout<<host_ip<<endl;

		}
	}
	sqlite3_free_table(dbResult);
	//11.4 get sin IP
	memset(cSql,0,1024);
	snprintf(Sql, 1024-1,"select distinct attack_code from Web_Attack_Action");
	dbResult1=NULL;
	nRow1=0;
	nColumn1=0;
	errMsg=NULL;
	char *strIP=NULL;
	ret = sqlite3_get_table(db, cSql, &dbResult1, &nRow1, &nColumn1, &errMsg);
	if(ret == SQLITE_OK)
	{
		index1 = nColumn1;
		for (i = 0; i < nRow1; i++)
        {
			
			strIP=dbResult1[index1];
			cout<<strIP<<endl;
			vtsinIP.push_back(strIP);
			index1++;

		}
	}
	sqlite3_free_table(dbResult1);
	memset(cSql,0,1024);
	snprintf(Sql, 1024-1,"select distinct attack_ip from Web_Attack_Action");
	
	ret = sqlite3_get_table(db, cSql, &dbResult1, &nRow1, &nColumn1, &errMsg);
	if(ret == SQLITE_OK)
	{
		index1 = nColumn1;
		for (i = 0; i < nRow1; i++)
        {
			
			strCode=dbResult1[index1];
			cout<<strCode<<endl;
			vtCode.push_back(strCode);
			index1++;

		}
	}
	sqlite3_free_table(dbResult1);
	for(it=vtCode.begin();it != vtCode.end(); it++)
	{
		for(it2=vtsinIP.begin();it2 != vtsinIP.end();it2++)
		{
			string strmin_time=NULL;
			string strmax_time=NULL;
			char *strAttackName=NULL;
			char sql[1024];
			char insertsql[1024];
			memset(sql,0,1024);
			memset(insertsql,0,1024);
			snprintf(Sql, 1024-1,"select attack_time from Web_Attack_Action where attack_code= '%s' and attack_ip= '%s'",*it,*it2);
			ret = sqlite3_get_table(db,sql, &dbResult, &nRow,&nColumn, &errMsg);
			if(ret == SQLITE_OK)
			{
				index = nColumn;
				v_Time.clear();
				for (int i = 0; i < nRow; i++)
				{
					char* strTime = dbResult[index];
					v_Time.push_back(strTime);
					index++;

				}
				if(v_Time.size()>0)
				{
					std::vector<string>min_time;
					auto min_time = min_element(v_Time.begin(), v_Time.end());
					auto max_time = max_element(v_Time.begin(), v_Time.end());
					strmin_time=*min_time;
					strmax_time=*max_time;
					if((*it).c_str()=="sql_injection")
					{
						strAttackName="<SQL注入>";
					}
					if((*it).c_str()=="scan_robots")
					{
						strAttackName="<扫描器入侵行为>";
					}
					if((*it).c_str()=="xss")
					{
						strAttackName="<XSS攻击>";
					}
					if((*it).c_str()=="struts2_remote_command_exe")
					{
						strAttackName="<struts2远程命令执行>";
					}
					if((*it).c_str()=="webshell")
					{
						strAttackName="<WebShell>";
					}
					memset(Uid, 0, sizeof(Uid));
					GetUUID(Uid, 36);
					snprintf(insertsql,1024-1,"insert into event_association_analysis values('%s', '%s', '%s', '%s', '%s', '%s', '','','','','','','','','','%s','%s')",Uid,host_ip,(*it2).c_str(),strAttackName,strmin_time.c_str(),strmax_time.c_str(),Mac,eventId);
					ret = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg);
					if(errMsg != NULL)
					{
						cout<<"insert into event_association_analysis fail"<<endl;
						sqlite3_free(errMsg);
					}
					
				}
			}
		}
	}


}
*/
void AttackStat(sqlite3* db, char *Mac, char *eventId)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	char Sql[1024];
	char Uid[36];

	char *cSql = "select attack_ip, attack_code, count(attack_code) from Web_Attack_Action GROUP BY attack_code, attack_ip";
	ret = sqlite3_get_table(db, cSql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
        {
			char *attack_ip = NULL;
			char *attack_code = NULL;
			char *count = NULL;
            for (j = 0; j < nColumn; j++)
            {
                //字段名:dbResult[j], 值:dbResult[index];
				if(j == 0)
					attack_ip = dbResult[index];
				else if(j == 1)
				{
					attack_code = dbResult[index];
					cout<<attack_code<<endl;
				}
					

				else 
					count = dbResult[index];
                index++;
            }
			int Num = atoi(count);
			memset(Uid, 0, sizeof(Uid));
			GetUUID(Uid, 36);
			memset(Sql, 0, sizeof(Sql));
			snprintf(Sql, 1024-1, "insert into Attack_Count(attack_count_id, attack_ip, attack_code, attack_num, mac_address, event_task_id) values('%s', '%s', '%s', '%d', '%s', '%s')", 
				Uid, attack_ip, attack_code, Num, Mac, eventId);
			ret = sqlite3_exec(db, Sql, NULL, NULL, &errMsg);
			if (ret != SQLITE_OK)
			{
				perror("insert Attack_Count err");
				sqlite3_free(errMsg);
			}
			
        }
		sqlite3_free_table(dbResult);	// 释放结果
	}

}
//攻击回溯分析
 void AtackBackAn(sqlite3* db, char *Ip,char *Mac, char *eventId)
 {
	vector<p_IpABN_> allABN;
 	vector<string> vip;
	vector<string>::iterator it;
	int ret;
	char ** dbResult = NULL;
	//根据可疑IP查询结果集
	char **dbResultweb=NULL;
	int nRowweb,nColumnweb;
	char * errMsgweb=NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	char * strIP=NULL;
	char Sql[1024];
	char Uid[36];

	char *cSql = "select ip_address from Source_Ip_Analysis";
	ret = sqlite3_get_table(db, cSql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
        {
			string ip (dbResult[index]);
			strIP=dbResult[index];
			if(ip.size()>=7)
			{
				vip.push_back(ip);
			}
			
			cout<<strIP<<"可疑IP"<<endl;
			index++;
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
		
	for(it = vip.begin(); it != vip.end(); it++)
	{
		
		int ret;
		char ** dbResult = NULL;
		int nRow, nColumn;
		int i, j, index;
		char * errMsg = NULL;

		char Sql[1024];
		char Uid[36];
		char sql[128];
		char insertsql[512];
		char *err_msg;
		memset(sql, 0, sizeof(sql));
		memset(Uid, 0, sizeof(char)*36);
		GetUUID(Uid, 36);
		p_IpABN_ pipABN = new IpABN_;
		memset(pipABN, 0, sizeof(IpABN_));
		strcpy(pipABN->ipAddress,(*it).c_str());
		snprintf(sql, 128-1, "select  attack_code from Web_Attack_Action where attack_ip= '%s'", (*it).c_str());
	//	cout<<sql <<endl;
		ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (i = 0; i < nRow; i++)
        	{
				char *attack_ip = NULL;
				char *attack_code = NULL;
				char *count = NULL;
            	for (j = 0; j < nColumn; j++)
            	{
					attack_code = dbResult[index];
				//	cout << "攻击类型"<<attack_code <<endl;
					if (strcmp(attack_code,"scan_robots" ) == 0)
					{
						if(strstr(pipABN->pointScans,"10,")==NULL)
						{
							sprintf(pipABN->pointScans,"%s%s",pipABN->pointScans,"10,");
							//cout<<pipABN->pointScans<<endl;
						}
					}
					else if (strcmp(attack_code,"passwd_attack" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"12,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"12,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"sql_injection" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"13,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"13,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"xss" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"14,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"14,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"java_ouin_stream" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"19,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"19,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"webshell" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"22,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"22,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"sensitive_file" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"17,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"17,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"file_include" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"15,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"15,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"struts2" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"18,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"18,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"shell_shock" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"16,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"16,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
					else if (strcmp(attack_code,"http_crlf" ) == 0)
					{
						if(strstr(pipABN->invadeAccess,"20,")==NULL)
						{
							sprintf(pipABN->invadeAccess,"%s%s",pipABN->invadeAccess,"20,");
							//cout<<"pipABN->invadeAccess="<<pipABN->invadeAccess<<endl;
						}
					}
                	index++;
    	       	}
	
       		 }
			sqlite3_free_table(dbResult);	// 释放结果

		}
		memset(insertsql,0,sizeof(insertsql));
		snprintf(insertsql,512-1,"insert into Recall_Result values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s', '%s')",Uid,pipABN->ipAddress,pipABN->pointScans, pipABN->invadeAccess, pipABN->drawPrivilege, pipABN->getInfo, pipABN->lookDest,
			pipABN->cleanMark, pipABN->creatBackDoor, pipABN->refuseServe,Ip, Mac, eventId);
		//int ret_ok = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
		int ret_ok = sqlite3_exec(db, insertsql, NULL, NULL, &err_msg);
		if(ret_ok != 0)
		{
			perror(err_msg);
			sqlite3_free(err_msg);
			//sqlite3_close(db);
		}
			//cout<<insertsql<<"cha ru "<<endl;
	}
 }
// 给压缩包添加校验， linuxrt
int addCheck(char *fileName)
{
	if(fileName == NULL)
		return -1;
	
	if(access(fileName, F_OK) != 0)
		return -2;
	
	FILE *fp = NULL;
	fp = fopen(fileName, "a+");
	if(fp == NULL)
	{
		perror("open zip file failed");
		return -3;
	}

	char *CheckCode = "linuxrt";
	fseek(fp, 0, SEEK_END);
	//int size = ftell(fp);
	if(fwrite(CheckCode, sizeof(char), 8, fp) <= 0)
		perror("write check code err");
	fclose(fp);

	return 0;
}

void ShowERR(WORD retcode)
{
	if (retcode == 0) return;
	printf("Error Code: %d\n", retcode);
}
/*
//2020.12.8 add check Rockey4
bool check()
{
	WORD handle[16], p1, p2, p3, p4, retcode;
	DWORD lp1, lp2;
	BYTE buffer[1024];
	DWORD dwLP2 = 0;
	//WORD rc[4];
	int i, j,k;
	int nKeyLen[2]={8,16} ;
	unsigned char keybuf[16];
	char str[1024];
	char hid[256];
	char cmd[] = "H=H^H, A=A*23, F=B*17, A=A+F, A=A+G, A=A<C, A=A^D, B=B^B, C=C^C, D=D^D";
	char cmd1[] = "A=A+B, A=A+C, A=A+D, A=A+E, A=A+F, A=A+G, A=A+H";
	char cmd2[] = "A=E|E, B=F|F, C=G|G, D=H|H";
	memset(hid,0,256);
	
	
	p1 = 0x44F6;
	p2 = 0x74E0;
	p3 = 0xE489;
	p4 = 0xEF88;


	retcode = Rockey(RY_FIND, &handle[0], &lp1, &lp2, &p1, &p2, &p3, &p4, buffer);
	if (retcode)
	{
		ShowERR(retcode);
		Rockey(RY_CLOSE,&handle[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	retcode = Rockey(RY_OPEN,&handle[0], &lp1, &lp2, &p1, &p2, &p3, &p4, buffer);
	if (retcode)
	{
		ShowERR(retcode);
		Rockey(RY_CLOSE,&handle[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	retcode = Rockey(RY_VERSION,&handle[0], &lp1, &lp2, &p1, &p2, &p3, &p4, buffer);
	if (retcode)
	{
		ShowERR(retcode);
		Rockey(RY_CLOSE,&handle[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	if (lp2 < 259)
	{	
		ShowERR(retcode);
		Rockey(RY_CLOSE,&handle[0],NULL,NULL,NULL,NULL,NULL,NULL,NULL);
		return 0;
	}
	return true;

}*/
void ShowMainCmdMenu()
{
	printf("\r\nPlease Input key pwd:");
	
}
//2020.12.9 user input password
void getUserInputstr(char *str)
{
	fflush(stdin);
	//char str[20];  //定义一个最大长度为19, 末尾是'\0'的字符数组来存储字符串
    printf("input z201 password:");
    fgets(str, 10, stdin);  //从输入流stdin即输入缓冲区中读取7个字符到字符数组str中
}
/*
//2020.12.9 add check Z201
bool checkZ201()
{	
	char *str;
	str =new char[20];
	memset(str,0,20);
	getUserInputstr(str);
	 printf("动态口令%s:",str);
	char authkey[51] = "llEE525A8016336BA9285E9B9464C8A7F638E204BEDB92D635";
	uint64_t authnum = 0;
    uint64_t currsucc = 0;
    int currdft = 0;
		time_t t;
	t=time((time_t *) 0);
	// 打开数据库
	char dbName[128];
	memset(dbName, 0, sizeof(dbName));
	snprintf(dbName, 128-1, "db/CONFIG");
	
	sqlite3 *db = NULL;
	int rc;
	rc = sqlite3_open(dbName, &db);
	if(rc)
	{
		perror("open database failed");
		return -1;
	}
	int ret;
	char ** dbResult = NULL;
	//根据可疑IP查询结果集
	char **dbResultweb=NULL;
	int nRowweb,nColumnweb;
	char * errMsgweb=NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	char * strIP=NULL;
	char Sql[1024];
	char Uid[36];
	CBase64 pBase64;
	int checkrs;
	char *cSql = "SELECT KeySeed from SEEDVECOR";
	ret = sqlite3_get_table(db, cSql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		
		for (i = 0; i < nRow; i++)
       		 {
			int dwseednumber;
			string strSEEDA (dbResult[nColumn + i*nColumn]);
			char *cstr = new char[strSEEDA.length() + 1];

			strcpy(cstr, strSEEDA.c_str());
			string strAseed = pBase64.Decode(cstr,strlen(cstr),dwseednumber);
			strcpy(authkey, strAseed.c_str());

			 //测试TOTP认证
			   checkrs=ET_CheckPwdz201(authkey, t, 0, 60, 0, 20, 0, 
				str, 6, &currsucc, &currdft);
			 if(checkrs==0)	
			    {
				printf("C200 OTP verify ok, currsucc: %llu\n", 
				    currsucc); 
				break;  
			    }
			  

		 }

	}
sqlite3_close(db);
    if(checkrs==0)
	{
	return true;
	}
	else
	{
	checkZ201();
	}	

  return true;
	
}*/
int main(int argc, char* argv[])
{
//2012.3.9 del check rockey4

	/*bool rs =check();
	
	if(!rs)
	{*/
		/*if(!checkZ201())
		{
		 printf("C200 OTP verify ok, currsucc");
		return 0;
		}*/

	//}
	
	
	char mac[100] = {0};
	memset(mac, 0, sizeof(mac));
	GetMacAddr(mac);
	char cIp[36];           // 本地ip
    	memset(cIp, 0, sizeof(cIp));
    	LocalIp(cIp, 36);
 	char Mac[100];
	memset(Mac,0,sizeof(Mac));
	strcat(Mac,mac);
	strcat(Mac,"~~");
	strcat(Mac,cIp);
	//snprintf(Mac,100-1,"%s","%s","%s",mac,"--",cIp);
	cout<<"mac --ip="<<mac<<endl;
	cout<<"mac --ip="<<cIp<<endl;
	cout<<"mac --ip="<<Mac<<endl;
	char *EventId = "12345678901234567890123456789012";

	system("rm -r /home/ydLinux");
	/*system("whoami >1.txt");
	 char * filename = "./1.txt";

   	 FILE *fp = NULL;
   	 fp = fopen(filename, "r");
   	 if(fp == NULL)
   	 {
      	  perror("open file failed");
       	 return 0;
   	 }

        char buf[256];
    	memset(buf, 0, sizeof(buf));

   
	    
    	if(fgets(buf, 255, fp) != NULL)
    	{
	 cout<<buf<<endl;
	}
	 fclose(fp);
   	 system("rm 1.txt");*/
	char cMakeResult[128];
	memset(cMakeResult, 0, sizeof(cMakeResult));
	//snprintf(cMakeResult, 128-1, "mkdir -p 采集工具/采集结果/%s/主机层", Mac);
	snprintf(cMakeResult, 128-1, "mkdir -p /home/ydLinux/result/%s/host", Mac);
	system(cMakeResult);
	cout<<cMakeResult<<endl;
	memset(cMakeResult, 0, sizeof(cMakeResult));
	snprintf(cMakeResult, 128-1, "mkdir -p /home/ydLinux/result/%s/WebAttackAction", Mac);
	system(cMakeResult);
	cout<<cMakeResult<<endl;
	memset(cMakeResult, 0, sizeof(cMakeResult));
	snprintf(cMakeResult, 128-1, "mkdir -p /home/ydLinux/result/%s/virus", Mac);
	system(cMakeResult);
	cout<<cMakeResult<<endl;	
	char cResult[128];
	memset(cResult, 0, sizeof(cResult));
	snprintf(cResult, 128-1, "/home/ydLinux/result/%s", Mac);

	chdir("build");
	if(access("db/hongtan004_linux.db", F_OK) != 0)
	{
		//system("pwd");
		cout << "db not existed" << endl;
		return -1;
	}

	char copyDb[128];
	memset(copyDb, 0, sizeof(copyDb));
	snprintf(copyDb, 128-1, "cp db/hongtan004_linux.db %s/host", cResult);
	system(copyDb);
	
	// 打开数据库
	char dbName[128];
	memset(dbName, 0, sizeof(dbName));
	snprintf(dbName, 128-1, "%s/host/hongtan004_linux.db", cResult);
	//char *sqlname="./hongtan004_linux.db";
	sqlite3 *db = NULL;
	int rc;
	rc = sqlite3_open(dbName, &db);
	if(rc)
	{
		perror("open database failed");
		return -1;
	}
 	
	cout<<"interinfo"<<endl;
	GetUnixSocket(db, Mac, EventId);
	GetInterInfo(db, Mac, EventId);
	//cout<<"本地IP"<<cIp<<endl;
	
cout << "virus info" << endl;

	// 病毒检测
	
	char cVirusResult[128];
	memset(cVirusResult, 0, sizeof(cVirusResult));
	
	snprintf(cVirusResult, 128-1, "/home/ydLinux/result/%s/virus", Mac);
	GetVirus(cVirusResult);
	cout << cVirusResult << endl;
	cout << "病毒扫描完成" << endl;
	// 主机日志
	cout << "host log" << endl;
	Getwtmporutmp(db, Mac, EventId);
	cout<<"安全日志开始获取 start"<<endl;
	Getsecure(db, Mac, EventId);
	cout<<"安全日志获取结束 end"<<endl;
	cout<<" update logoip"<<endl;
	UpdateIP(db);
	UpdateSUuser(db);
	GetPassword_violence_crack(db, Mac, EventId);
	GetSucLog(db,Mac, EventId);
	cout<<"安全日志分析结束 end"<<endl;
	GetInstallLog(db, Mac, EventId);
	SetabnormalLog(db);
	cout << "Web Info" << endl;
	
	char cWebType[1024];
	memset(cWebType, 0, sizeof(char)*1024);
	// 获取web信息和文件信息
	char cWebResult[128];
	memset(cWebResult, 0, sizeof(cWebResult));
	
	snprintf(cWebResult, 128-1, "home/ydLinux/result/%s/WebAttackAction", Mac);
	WebAndFileinfo(db, EventId, cWebType, cWebResult,Mac);
	cout<<cWebResult<<endl;
	

	
	cout << "history cmd" << endl;

	// 历史命令
	Gethistory();
//	system("sudo history >history");
	cout << "" << endl;


	cout << "write result to db" << endl;

	cout << "history cmd result" << endl;

	HistoryResultToDb(db, EventId);
	system("rm history");
	
	// 用户信息
	UserInfoAndToDB(db, Mac, EventId);
	
	mapMonth.insert(pair<string,int>("Jan",1));
	mapMonth.insert(pair<string,int>("Feb",2));
	mapMonth.insert(pair<string,int>("Mar",3));
	mapMonth.insert(pair<string,int>("Apr",4));
	mapMonth.insert(pair<string,int>("May",5));
	mapMonth.insert(pair<string,int>("Jun",6));
	mapMonth.insert(pair<string,int>("Jul",7));
	mapMonth.insert(pair<string,int>("Aug",8));
	mapMonth.insert(pair<string,int>("Sep",9));
	mapMonth.insert(pair<string,int>("Oct",10));
	mapMonth.insert(pair<string,int>("Nov",11));
	mapMonth.insert(pair<string,int>("Dec",12));

	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_FileIncludeAttack.ydtxt", "file_include"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_HttpCRLFAttack.ydtxt", "http_crlf"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_IncHTTPAttack.ydtxt", "domain"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_JavaouinStreamAttack.ydtxt", "java_ouin_stream"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_PasswdAttackAttack.ydtxt", "passwd_attack"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_ScanRobotsAttack.ydtxt", "scan_robots"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_SensitiveFileAttack.ydtxt", "sensitive_file"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_ShellShockAttack.ydtxt", "shell_shock"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_SQLInjectionAttack.ydtxt", "sql_injection"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_Struts2Attack.ydtxt", "struts2"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_WebShellAttack.ydtxt", "webshell"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_XSSAttack.ydtxt", "xss"));
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_Struts2RemoteCommandExeAttack.ydtxt","struts2_remote_command_exe"));	//	Struts2远程命令执行	
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_Struts2AttackAttack.ydtxt","struts2_attack"));	//Struts2威胁攻击检测	
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_urlJumpAttack.ydtxt","urljump"));	//Struts2威胁攻击检测
	vFileAttackType.push_back(pair<string, string>("watchertrack_attack_CommandExecutionAttack.ydtxt", "command_execution"));

	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_AWVSAttack.ydtxt", "AWVS"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_NetsparkerAttack.ydtxt", "Netsparker"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_AppscanAttack.ydtxt", "Appscan"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_WebinspectAttack.ydtxt", "Webinspect"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_RsasAttack.ydtxt", "Rsas"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_NessusAttack.ydtxt", "Nessus"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_SQLMapAttack.ydtxt", "SQLMap"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_HTTrackAttack.ydtxt", "HTTrack"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_dirbusterAttack.ydtxt", "dirbuster"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_pangolinAttack.ydtxt", "pangolin"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_nmapAttack.ydtxt", "nmap"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_hydraAttack.ydtxt", "hydra"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_w3afAttack.ydtxt","w3af"));	//	Struts2远程命令执行	
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_owaspAttack.ydtxt","owasp"));	//Struts2威胁攻击检测	
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_NiktoAttack.ydtxt","Nikto"));	//Struts2威胁攻击检测
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_havijAttack.ydtxt", "havij"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_zmeuAttack.ydtxt", "zmeu"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_BabyKrokodilAttack.ydtxt", "BabyKrokodil"));
	vAttackToolType.push_back(pair<string, string>("watchertrack_attack_httperfAttack.ydtxt", "httperf"));

	cout << "Web result" << endl;

	WebResultToDb(db, cResult, EventId);

	cout << "virus result" << endl;

	virResultToDb(db, cResult, EventId);

	cout << "Ip&time" << endl;
	// 获取攻击ip和时间范围
	vector<pAttackIP> vtAttackIP;
	GetAttackIPandTime(db, Mac, vtAttackIP, EventId);

	// 攻击行为统计（Attack_Count表)
	AttackStat(db, Mac, EventId);
	//GetAttackInfo(db,Mac, EventId);
	cout << "process" << endl;
	// 获取进程信息并入库
	getProcess(db, Mac, vtAttackIP, EventId);

	cout << "sus file" << endl;
	// 可疑文件
	SuspiciousFile(db, Mac, vtAttackIP, EventId);

	cout << "base info" << endl;
	// 基础信息
	GetBaseInfo(db, Mac, EventId, cWebType);

	cout << "uuid" << endl;
	// 写入uuid
	updateUUID(db);
	
	//攻击回溯分析
	cout <<"AtackBackAn"<< endl;
	AtackBackAn(db, cIp,Mac, EventId);
	//cout<<myip<<"bendi ip"<<endl;
	sqlite3_close(db);
	system("chmod -R 777 /home/ydLinux/");
	cout << "done" << endl;

	//if(access("./采集工具.zip", F_OK) == 0)
		//system("rm 采集工具.zip");
	
	// 压缩采集结果文件夹
	//system("zip -r 采集工具.zip 采集工具");

	// 给压缩包添加校验  linuxrt
	//addCheck("./采集工具.zip");

	return 0;
}
